<template>
  <div class="myPage">
    <div class="info-card">
      <el-card class="box-card" shadow="hover">
        <div class="card-title text-middle-up">基本信息</div>
        <div class="card-content">
          <el-form 
            ref="baseinfoRuleRef" 
            :model="state.baseInfo" 
            status-icon 
            :rules="baseInfoRules" 
            label-width="120px"
            class="demo-ruleForm" 
            :disabled="!state.updateBaseInfo"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="state.baseInfo.name" />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-select v-model="state.baseInfo.gender" class="m-2" placeholder="Select">
                <el-option 
                  v-for="item in state.genderOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>

            <el-form-item label="职称" prop="level">
              <el-input v-model="state.baseInfo.level" />
            </el-form-item>

            <el-form-item label="工作单位" prop="workplace">
              <el-input v-model="state.baseInfo.workplace" />
            </el-form-item>

            <el-form-item label="地址" prop="address">
              <el-input v-model="state.baseInfo.address" />
            </el-form-item>

            <el-form-item label="擅长领域" prop="tag">
              <el-input v-model="state.baseInfo.tag" />
            </el-form-item>

            <el-form-item label="心理咨询资格证" prop="certificate">
              <el-input v-model="state.baseInfo.certificate" />
            </el-form-item>
          </el-form>

          <div v-if="!state.updateBaseInfo" class="update-form mouse-hover-pointer" @click="updateinfo('baseInfo')">
            修改基本信息
            <el-icon><DArrowRight /></el-icon>
          </div>
          <div v-else class="update-form">
            <el-button type="primary" @click="cancelUpdate">取消</el-button>
            <el-button type="primary" @click="updateinfoSubmit(baseinfoRuleRef)">确认</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <div class="info-card">
      <el-card class="box-card" shadow="hover">
        <div class="card-title text-middle-up">账号信息</div>
        <div class="card-content">
          <el-form 
            ref="accountInfoRuleRef" 
            :model="state.baseInfo" 
            status-icon 
            :rules="accountInfoRules"
            label-width="120px" 
            class="demo-ruleForm"
          >
            <el-form-item label="手机号" prop="mobile">
              <div class="form-item">
                <el-input 
                  v-model="state.baseInfo.mobile" 
                  :disabled="!state.updateAccountInfo.updatePhone" 
                />
                <div 
                  v-if="!state.updateAccountInfo.updatePhone" 
                  class="text mouse-hover-pointer"
                  @click="updateinfo('updatePhone')"
                >
                  更换手机
                </div>
                <div v-else class="text">
                  <el-button type="primary" @click="updateinfoSubmit(accountInfoRuleRef, 'mobile')">确认</el-button>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <div class="form-item">
                <el-input 
                  v-model="state.baseInfo.email" 
                  :disabled="!state.updateAccountInfo.updateEmail" 
                />
                <div 
                  v-if="!state.updateAccountInfo.updateEmail" 
                  class="text mouse-hover-pointer"
                  @click="updateinfo('updateEmail')"
                >
                  更换邮箱
                </div>
                <div v-else class="text">
                  <el-button type="primary" @click="updateinfoSubmit(accountInfoRuleRef, 'email')">确认</el-button>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <div class="form-item">
                <el-input 
                  type="password" 
                  disabled 
                  value="********"
                />
                <div 
                  class="text mouse-hover-pointer"
                  @click="goToRePassword"
                >
                  修改密码
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import { useUserInfoStore } from '@/stores/info/index'
import { ElMessage } from 'element-plus'
import CounselorApi from '@/api/counselor'
import type { UserCounselorData } from '@/api/counselor/types'
import { useRouter } from 'vue-router'
import { GoPageName } from "@/enums"

const userInfoStore = useUserInfoStore()
const router = useRouter()

interface State {
  baseInfo: UserCounselorData;
  updateBaseInfo: boolean;
  updateAccountInfo: {
    updatePhone: boolean;
    updateEmail: boolean;
  };
  genderOptions: Array<{ value: number; label: string }>;
}

const state = reactive<State>({
  baseInfo: {
    user_id: userInfoStore.userInfo.user_id,
    name: '',
    gender: 1,
    mobile: '',
    email: '',
    address: '',
    level: '',
    workplace: '',
    tag: '',
    certificate: ''
  },
  updateBaseInfo: false,
  updateAccountInfo: {
    updatePhone: false,
    updateEmail: false
  },
  genderOptions: [
    { value: 1, label: '男' },
    { value: 2, label: '女' }
  ]
})

// 表单校验规则
const baseinfoRuleRef = ref<FormInstance>()
const baseInfoRules = reactive<FormRules>({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  level: [{ required: true, message: '请输入职称', trigger: 'blur' }],
  workplace: [{ required: true, message: '请输入工作单位', trigger: 'blur' }]
})

const accountInfoRuleRef = ref<FormInstance>()
const accountInfoRules = reactive<FormRules>({
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
})

// 获取咨询师信息
const getCounselorInfo = async () => {
  try {
    const res = await CounselorApi.getUserCounselor(state.baseInfo.user_id)
    if (Array.isArray(res.data) && res.data.length > 0) {
      // 获取数组的第一个元素
      const counselorData = res.data[0]
      // 更新状态
      state.baseInfo = counselorData
    } else {
      ElMessage.warning('获取信息不完整')
    }
  } catch (error) {
    console.error('获取咨询师信息失败:', error)
    ElMessage.error('获取信息失败')
  }
}

// 修改信息相关显示
const updateinfo = (type: string) => {
  if (type === 'baseInfo') {
    state.updateBaseInfo = true
  } else if (type === 'updatePhone') {
    state.updateAccountInfo.updatePhone = true
    state.updateAccountInfo.updateEmail = false
  } else if (type === 'updateEmail') {
    state.updateAccountInfo.updateEmail = true
    state.updateAccountInfo.updatePhone = false
  }
}

// 取消更新
const cancelUpdate = () => {
  state.updateBaseInfo = false
  getCounselorInfo() // 重新获取信息
}

// 提交修改
const updateinfoSubmit = async (formEl: FormInstance | undefined, type?: string) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 确保 updateData 包含必需的 user_id
        const updateData: UserCounselorData = {
          user_id: state.baseInfo.user_id,
          name: state.baseInfo.name,
          gender: state.baseInfo.gender,
          mobile: state.baseInfo.mobile,
          email: state.baseInfo.email,
          address: state.baseInfo.address,
          level: state.baseInfo.level,
          workplace: state.baseInfo.workplace,
          tag: state.baseInfo.tag || '',  // 提供默认值
          certificate: state.baseInfo.certificate || '' // 提供默认值
        }
        
        // 根据类型选择要更新的字段
        const finalUpdateData: UserCounselorData = {
          ...updateData,
          ...(type === 'mobile' ? { mobile: state.baseInfo.mobile } :
              type === 'email' ? { email: state.baseInfo.email } :
              {
                name: state.baseInfo.name,
                gender: state.baseInfo.gender,
                level: state.baseInfo.level,
                workplace: state.baseInfo.workplace,
                address: state.baseInfo.address,
                tag: state.baseInfo.tag || '',
                certificate: state.baseInfo.certificate || ''
              })
        }

        console.log('准备更新的数据:', finalUpdateData)
        const res = await CounselorApi.updateCounselor(state.baseInfo.user_id, finalUpdateData)
        
        if (res) {
          ElMessage.success('更新成功')
          state.updateBaseInfo = false
          state.updateAccountInfo.updatePhone = false
          state.updateAccountInfo.updateEmail = false
          await getCounselorInfo()
        } else {
          ElMessage.error('更新失败')
        }
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败')
      }
    }
  })
}

// 跳转到修改密码页面
const goToRePassword = () => {
  router.push({
    name: 'counselorSettings',
    params: {
      path: GoPageName.REPASSWORD
    }
  })
}

onMounted(() => {
  getCounselorInfo()
})
</script>

<style scoped>
.info-card {
  margin: 20px auto;
  width: 777px;
}

.box-card {
  min-height: 200px;
}

.card-title {
  text-align: left;
  border-bottom: 1px solid black;
  width: 75px;
}

.card-content {
  margin-top: 20px;
}

.update-form {
  color: rgb(64, 149, 229);
  text-align: right;
}

.form-item {
  display: flex;
  width: 100%;
}

.form-item .el-input {
  flex: 5;
}

.form-item .text {
  flex: 1;
  color: rgb(64, 149, 229);
}

.mouse-hover-pointer {
  cursor: pointer;
}
</style>